<?php
namespace app\api\controller\wanlshop;
use addons\wanlshop\library\WanlSdk\Common;
use app\common\controller\Api;
use fast\Tree;
use think\Db;
class Cards extends Api
{
	protected $noNeedLogin = ['lists', 'detail'];
	protected $noNeedRight = ['*'];
	protected $excludeFields = "";

	public $card_type_name_arr = ['有限次卡','不限次卡','通卡','充值卡','折扣卡'];
	/**
	 * 获取卡项列表
	 */
	public function lists()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		$params = $this->request->param();
		$page = $params['page'];
		$type = json_decode($params['filter'], true)['category_id'];
		$limit = 10;
		$shop_id = 1;
		$where = ['type'=>$type,'shop_id'=>$shop_id,'price'=>['>',0],'activity_type'=>'goods','status'=>'normal'];
		$list = model('app\admin\model\item\Item')
		        ->where($where)
		        ->where(function ($query) use ($shop_id) {
		        	$query->where('stock', '0')
		        	      ->whereOr(function ($query) use ($shop_id) {
		        	          $query->where('stock', '1')
		        	                ->whereRaw("FIND_IN_SET($shop_id, shop_ids)");
		        	      });
		        })
		        ->order('createtime', 'desc')
		        ->paginate($limit, false, ['page' => $page])->each(function (&$v) {
		        	if (!isset($v['card_service'])) {
                        $v['card_service'] = '';
                    }
                    if (!isset($v['time'])) {
                        $v['time'] = '';
                    }
                    if (!isset($v['type_name'])) {
                        $v['type_name'] = '';
                    }
                    $v['type_name'] = $this->card_type_name_arr[$v['type']-1];
                    if ($v['validity'] == 0) {
                        $v['time'] = '永久有效';
                    }elseif ($v['validity'] == 1) {
                        $v['time'] = date('Y-m-d', $v['validitytime']);
                    }elseif ($v['validity'] == 2) {
                        $v['time'] = '购买后' . $v['validitydays'] . '天内有效';
                    }elseif ($v['validity'] == 3) {
                        $v['time'] = '首次使用后' . $v['validitydays'] . '天内有效';
                    }
                    $ser = Db::name('item_info i')->where('i.item_id', $v['id'])
                           ->join('wanlshop_goods s', 'i.goods_id = s.id', 'left')->select();
                    foreach ($ser as $kk => $vv) {
                    	$v['card_service'] .= $vv['title'] . '、';
                    }
                    return $v;
		        })->toArray();
		foreach ($list['data'] as $key => $value) {
			$list['data'][$key]['unit_price'] = 0;
			if ($value['type'] != 4 && $value['total'] != 0) {
                $list['data'][$key]['unit_price'] = floatval($value['price']/$value['total']);
            }
            //卡项失效
            if ($value['validity'] == 1 && $value['validitytime'] < time()) {
                unset($list['data'][$key]);
            }
        }
        $this->success('返回成功', $list);
	}

	/**
	 * 获取卡项详情
	 */
	public function detail()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		$id = $this->request->request("id");
		$where = ['id'=>$id,'price'=>['>',0],'activity_type'=>'goods','status'=>'normal'];
		$info = model('app\admin\model\item\Item')
		        ->where($where)
		        ->find()->toArray();
		if(empty($info))
		{
			$this->error(__('对不起当前卡项不存在！'));
			exit();
		}
		$info['type_name'] = $this->card_type_name_arr[$info['type']-1];
		if ($info['validity'] == 0) {
            $info['time'] = '永久有效';
        }elseif ($info['validity'] == 1) {
            $info['time'] = date('Y-m-d', $info['validitytime']);
        }elseif ($info['validity'] == 2) {
            $info['time'] = '购买后' . $info['validitydays'] . '天内有效';
        }elseif ($info['validity'] == 3) {
            $info['time'] = '首次使用后' . $info['validitydays'] . '天内有效';
        }
        $ser = Db::name('item_info i')->where('i.item_id', $info['id'])
               ->join('wanlshop_goods s', 'i.goods_id = s.id', 'left')->select();
        $card_service_str = '';
        $card_service_arr = [];
        foreach ($ser as $kk => $vv) {
        	$card_service_str .= $vv['title'] . '、';
        	$card_service_arr[] = $vv['title'];
        }
        $info['card_service_str'] = $card_service_str;
        $info['card_service_arr'] = $card_service_arr;
        if ($info['type'] != 4  && $info['total'] != 0) {
        	$info['unit_price'] = floatval($info['price']/$info['total']);
        }
        //卡项失效
        if ($info['validity'] == 1 && $info['validitytime'] < time()) {
        	$this->error(__('对不起当前卡项失效！'));
			exit();
		}
		$info['images'] = [$info['image']];
		$this->success('返回成功', $info);
	}

	/**
	 * 查询确认订单信息
	 */
	public function getOrderInfo()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		$params = $this->request->param();
		$id = $params['id'];
		$number = $params['number'];
		$where = ['id'=>$id,'price'=>['>',0],'activity_type'=>'goods','status'=>'normal'];
		$info = model('app\admin\model\item\Item')
		        ->where($where)
		        ->find()->toArray();
		if(empty($info))
		{
			$this->error(__('对不起当前卡项不存在！'));
			exit();
		}
		$info['type_name'] = $this->card_type_name_arr[$info['type']-1];
		if ($info['validity'] == 0) {
		    $info['time'] = '永久有效';
		}elseif ($info['validity'] == 1) {
		    $info['time'] = date('Y-m-d', $info['validitytime']);
		}elseif ($info['validity'] == 2) {
		    $info['time'] = '购买后' . $info['validitydays'] . '天内有效';
		}elseif ($info['validity'] == 3) {
		    $info['time'] = '首次使用后' . $info['validitydays'] . '天内有效';
		}
		$ser = Db::name('item_info i')->where('i.item_id', $info['id'])
		       ->join('wanlshop_goods s', 'i.goods_id = s.id', 'left')->select();
		$card_service_str = '';
		$card_service_arr = [];
		foreach ($ser as $kk => $vv) {
			$card_service_str .= $vv['title'] . '、';
			$card_service_arr[] = $vv['title'];
		}
		$info['card_service_str'] = $card_service_str;
		$info['card_service_arr'] = $card_service_arr;
		if ($info['type'] != 4) {
			$info['unit_price'] = floatval($info['price']/$info['total']);
		}
		//卡项失效
		if ($info['validity'] == 1 && $info['validitytime'] < time()) {
			$this->error(__('对不起当前卡项失效！'));
			exit();
		}
		// 数量
		$info['number'] = $number;
		//查询店铺
		$info['shop_name'] = Db::name('wanlshop_shop')->where(['id' => $info['shop_id']])->value('shopname');
		//总价
		$info['allsub'] = bcmul($info['price'], $info['number'], 2);
		$info['token'] = Common::creatToken('orderToken_'. $this->auth->id);
		$this->success('返回成功', $info);
	}

	/**
	 * 添加卡项订单
	 */
	public function addOrder()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		$params = $this->request->param();
		$user_id = $this->auth->id; // 用户ID
		// 数据库事务操作
		Db::startTrans();
		try {
			// 生成订单
			$order = new \app\api\model\wanlshop\Order;
			$order->data_type = 'cards';
			$order->user_id = $user_id;
			$order->shop_id = $params['shop_id'];
			$order->order_no = $params['shop_id'].$user_id;
			$order->price = $params['allsub'];
			$order->save_prcie = $params['allsub'];
			$order->actual_price = $params['allsub'];
			if(isset($params['remarks']))
			{
				$order->remarks = $params['remarks'];
			}
			if(!$order->save()){
				Db::rollback();
				$this->error(__('订单添加失败'));
			    exit();
			}
			//卡项
			for($i = 0; $i < $params['number']; $i++)
			{
				$item_data = [
					'item_id' => $params['id'],
					'order_id' => $order->id,
					'shop_id' => $params['shop_id'],
					'user_id' => $user_id,
					'category_id' => $params['category_id'],
					'type' => $params['type'],
					'name' => $params['name'],
					'code' => $params['code'],
					'consumption' => $params['consumption'],
					'actual_price' => $params['price'],
					'save_price' => $params['price'],
					'price' => $params['price'],
					'specs' => $params['specs'],
					'image' => $params['image'],
					'gift'  => $params['gift'],
					'spent' => $params['price'],
					'total' => $params['price']+$params['gift'],
					'validity' => $params['validity'],
					'validitydays' => $params['validitydays'],
					'shop_ids' => $params['shop_ids'],
					'stock' => $params['stock'],
					'activity' => $params['activity'],
					'distribution' => $params['distribution'],
					'flag'=> $params['flag'],
					'activity_type' => $params['activity_type'],
					'staff_ids' => '',
					'createtime' => time()
				];
				if ($params['validity'] == 0){
                    $item_data['validitytime'] = 9999;
                }
                if ($params['validity'] == 1){
                    $item_data['validitytime'] = $params['validitytime'];
                }
                if ($params['validity'] == 2){
                    $item_data['validitytime'] = time() + $params['validitydays'] * 24 * 60 * 60;
                }
                $item_data['status'] = 'hidden';
                if($params['type'] == 1)
                {
                	$item_data['spent'] = $params['total'];
                	$item_data['total'] = $params['total'];
                }
                $item_id = Db::name('wanlshop_order_item')->insertGetId($item_data);
                if(!$item_id){
                	Db::rollback();
                	$this->error(__('订单添加失败'));
			        exit();
                }
                if($params['type'] != 4)
                {
                	$sku_list = Db::name('item_info')->where(['item_id' => $params['id']])->select();
                	$all_total = 0;
                	foreach ($sku_list as $_kk => $_vv){
                		$all_total += $_vv['total'];
                	}
                	foreach ($sku_list as $kk => $vv){
                		$item_info = [
                			'order_item_id' => $item_id,
                			'item_id' => $params['id'],
                			'order_id' => $order->id,
                			'type' => $vv['type'],
                			'goods_id' => $vv['goods_id'],
                			'sku_id' => $vv['sku_id'],
                			'total' => $vv['total'],
                			'spent' => $vv['total'],
                			'createtime' => time(),
                		];
                		$item_info['price'] = number_format(($params['price'] * ($vv['total']/$all_total))/$vv['total'], 2);
                		$item_info['status'] = 'hidden';
                		$res = Db::name('wanlshop_order_item_info')->insert($item_info);
                		if(!$res || empty($res)){
                			Db::rollback();
                			$this->error(__('订单添加失败'));
			                exit();
                		}
                	}
                }

			}
			// 生成支付
			$payList[] = [
				'user_id' => $user_id,
				'shop_id' => $params['shop_id'],
				'order_id'  => $order->id,
				'order_no'  => $order->order_no,
				'pay_no' => $order->order_no,
				'type' => 'goods', // 1.0.8升级
				'price'  => $params['allsub'] <= 0 ? 0.01 : $params['allsub'],  // 支付价格，系统要求至少支付一分钱
				'order_price' => $params['allsub'], // 订单总金额
				'coupon_price' => 0,  // 优惠券金额
			    'freight_price' => 0, // 快递费
			    'discount_price' => 0, // 优惠金额
			    'number'  => $params['number']
			];
			$result = model('app\api\model\wanlshop\Pay')->saveAll($payList);
			if(empty($result))
			{
				Db::rollback();
				$this->error(__('订单添加失败'));
			    exit();
			}
			Db::commit();
		    $this->success('返回成功', ['list' => $result,'token' => Common::creatToken('orderToken_'. $this->auth->id)]);
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}

	}
}